class Cart < ActiveRecord::Base
  has_many :cart_items , :dependent=>:delete_all
  has_many :products,:through=>:cart_items

  def total
    cart_items.inject(0){|sum,item| item.price * item.amount + sum}
  end

  #如果购物车中存在该产品，则增加其数量，否则在购物车中添加该产品
  def add(product_id)
    item=cart_items.find_by_product_id(product_id)    
    if item
      item.increment!("amount")
    else
      item=cart_items.create(:product_id=>product_id,:amount=>1,:price=>Product.find(product_id).price)
    end
    item
  end

  def remove(cart_item_id)
    item = cart_items.find(cart_item_id)
    if item.amount<=1
      item.destroy
    else
      item.decrement!("amount")    
    end
    item
  end
end
